import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import cryptoUtils from '@/utils/crypto'


// 模拟用户数据API调用
const fetchUserInfo = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: 1,
        username: 'admin1',
        name: '管理员',
        email: 'admin@example.com',
        phone: '13800138000',
        department: '信息技术部',
        roles: ['管理员', '操作员'],
        createTime: '2023-01-15'
      })
    }, 500)
  })
}

export const useUserStore = defineStore('user', () => {

  const userInfo = ref(null)
  const token = ref('')

  const decryptUser = computed(() => {
    if (userInfo.value) {
      return cryptoUtils.decrypt(userInfo.value)
    }
    return {}
  }
  )

  const setEncryptUser = (info) => {
    userInfo.value = cryptoUtils.encrypt(info)
  }

  const setUserInfo = (info) => {
    decryptUser.value = info
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const info = await fetchUserInfo()
      setUserInfo(info)
      return info
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = async (newInfo) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      setUserInfo({ ...decryptUser.value, ...newInfo })
      return true
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
  }

  return {
    userInfo,
    decryptUser,
    token,
    setUserInfo,
    setEncryptUser,
    setToken,
    getUserInfo,
    updateUserInfo,
    clearUserInfo
  }
}, { persist: true }) // 使用持久化存储
